package com.mojo.concurrent.volatiles;

import java.util.StringJoiner;

/**
 * volatile可见性示例，反证法
 *
 * @author <a href="mailto:sjj@jianzhimao.com">mojo</a>
 * copyright (C), 2013-2022, 广州九尾信息科技有限公司
 * @date 2022/3/17 17:07
 */
public class Volatile1 {
    int a = 0;
    volatile boolean b = false;

    private void set() {
        try {
            a = 1;
            Thread.sleep(1000L);
            b = true;
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private void get() {
        if (b) {
            a = 2;
            System.out.println(a);
        }
    }


    static Volatile1 v1 = new Volatile1();

    @Override
    public String toString() {
        return new StringJoiner(", ", Volatile1.class.getSimpleName() + "[", "]").add("a=" + a).add("b=" + b).toString();
    }

    public static void main(String[] args) {

        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                v1.set();
            }
        });
        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                v1.get();
            }
        });
        t1.start();
        t2.start();
        try {
            t1.join();
            t2.join();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

    }
}
